package way.learning.zz.source;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * <pre>
 * Created with IntelliJ IDEA.
 * User: zhengzhi
 * Date: 2017/9/4
 * Time: 17:34
 * To change this template use File | Settings | File Templates.
 * </pre>
 *
 * @author Administrator
 */
public class FtpDirectory  implements PolledDirectory {


    private String host;
    private int port;
    private String workingDirectory;
    private String username;
    private String password;

    //构造函数
    public FtpDirectory(String host, int port, String workingDirectory, String username, String password) {
        this.host = host;
        this.port = port;
        this.workingDirectory = workingDirectory;
        this.username = username;
        this.password = password;
    }

    /**
     * 返回工作目录workingDirectory下的文件
     */
    public Set<FileElement> listFiles() throws IOException {
        FTPClient ftpClient = null;
        try{
            //构造ftpClient，连接到远程ftp服务器
            ftpClient = new FTPClient();
            ftpClient.connect(host,port);
            ftpClient.enterLocalPassiveMode();

            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                ftpClient.disconnect();
                throw new IOException("Exception when connecting to FTP Server: " + ftpClient);
            }

            //登录远程ftp服务器
            ftpClient.login(username, password);

            Set<FileElement> result = new LinkedHashSet<FileElement>();
            for(FTPFile file : ftpClient.listFiles(workingDirectory)){
                result.add(new FtpFile(file));
            }
            return result;
        } catch (Exception e){
            throw new IOException(e);
        } finally {
            try {
                if(ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            } catch(Throwable ioe) {
                // do nothing
            }
        }
    }
}
